<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { permissionApi } from '../../api'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  type: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  code: '',
  type: 1,
  description: '',
  status: 1,
  parentId: null,
  path: '',
  component: '',
  icon: '',
  sort: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 权限类型选项
const typeOptions = [
  { label: '菜单', value: 1 },
  { label: '按钮', value: 2 }
]

// 父级权限选项
const parentOptions = ref([])

// 获取父级权限选项
const fetchParentOptions = async () => {
  try {
    const res = await permissionApi.getAllPermissions() // 使用获取所有权限的接口
    if (res && Array.isArray(res)) {
      parentOptions.value = res.filter(permission => permission.type === 1) // 只获取菜单类型的权限作为父级选项
      // 添加顶级权限选项
      parentOptions.value.unshift({ id: 0, name: '顶级权限' })
    } else {
      console.error('获取父级权限选项失败: 数据格式不正确', res)
      ElMessage.error('获取父级权限选项失败')
    }
  } catch (error) {
    console.error('获取父级权限选项失败:', error)
    ElMessage.error('获取父级权限选项失败')
  }
}

// 表单引用
const formRef = ref()

// 初始化
onMounted(() => {
  fetchData()
  fetchParentOptions()
})

// 获取表格数据
const fetchData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const res = await permissionApi.getPermissionList(params)
    console.log('获取权限列表响应:', res)
    if (res.code === 200) {
      tableData.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加权限'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 显示编辑对话框
const showEditDialog = (row: any) => {
  dialogTitle.value = '编辑权限'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  form.id = row.id
  form.name = row.name
  form.code = row.code
  form.type = row.type
  form.description = row.description
  form.status = row.status
  form.parentId = row.parentId
  form.path = row.path
  form.component = row.component
  form.icon = row.icon
  form.sort = row.sort
}

// 删除权限
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    try {
      const res = await permissionApi.deletePermission(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败')
    }
  } catch {
    // 用户取消删除操作
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    try {
      let res
      if (form.id) {
        // 编辑权限
        res = await permissionApi.updatePermission(form.id, form)
      } else {
        // 添加权限
        res = await permissionApi.addPermission(form)
      }
      
      if (res.code === 200) {
        ElMessage.success(form.id ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        fetchData()
        fetchParentOptions() // 更新父级权限选项
      } else {
        ElMessage.error(res.message || (form.id ? '编辑失败' : '添加失败'))
      }
    } catch (error) {
      console.error(form.id ? '编辑权限失败:' : '添加权限失败:', error)
      ElMessage.error(form.id ? '编辑权限失败' : '添加权限失败')
    }
  } catch {
    // 表单验证失败
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.name = ''
  form.code = ''
  form.type = 1
  form.description = ''
  form.status = 1
  form.parentId = null
  form.path = ''
  form.component = ''
  form.icon = ''
  form.sort = 0
}

// 状态格式化
const statusFormatter = (row: any) => {
  return row.status === 1 ? '启用' : '禁用'
}

// 状态标签类型
const statusTagType = (status: number) => {
  return status === 1 ? 'success' : 'danger'
}

// 权限类型格式化
const typeFormatter = (row: any) => {
  return row.type === 1 ? '菜单' : '按钮'
}

// 权限类型标签类型
const typeTagType = (type: number) => {
  return type === 1 ? 'primary' : 'success'
}

// 父级权限格式化
const parentFormatter = (row: any) => {
  if (row.parentId === null || row.parentId === 0) {
    return '顶级权限'
  }
  const parent = parentOptions.value.find(item => item.id === row.parentId)
  return parent ? parent.name : '未知'
}
</script>

<template>
  <div class="permission-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择权限类型" clearable>
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加权限</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" width="150" />
        <el-table-column prop="code" label="权限编码" width="180" />
        <el-table-column prop="type" label="权限类型" width="100">
          <template #default="{ row }">
            <el-tag :type="typeTagType(row.type)">
              {{ typeFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="parentId" label="父级权限" width="120">
          <template #default="{ row }">
            {{ parentFormatter(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="150" />
        <el-table-column prop="component" label="组件" width="150" />
        <el-table-column prop="icon" label="图标" width="100" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级权限">
          <el-select v-model="form.parentId" placeholder="请选择父级权限" clearable>
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="路径" v-if="form.type === 1">
          <el-input v-model="form.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="组件" v-if="form.type === 1">
          <el-input v-model="form.component" placeholder="请输入组件" />
        </el-form-item>
        <el-form-item label="图标" v-if="form.type === 1">
          <el-input v-model="form.icon" placeholder="请输入图标" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.permission-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.operation-area {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>